package com.thinktank.controller;

import static com.thinktank.util.DbUtil.*;

import java.io.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.oreilly.servlet.*;
import com.oreilly.servlet.multipart.*;
import com.thinktank.dao.*;
import com.thinktank.vo.*;

public class NoticeRegProcessController implements Controller {
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 파일 업로드 기본 세팅
		ServletContext sc = request.getServletContext();
		String path = sc.getRealPath("\\upload");
		String encType = "utf-8";
		int maxSize = 5 * 1024 * 1024;
		File targetDir = new File(path);
		if (!targetDir.exists())
			targetDir.mkdirs();

		request.setCharacterEncoding("utf-8");

		MultipartRequest multi = new MultipartRequest(request, path, maxSize,
				encType, new DefaultFileRenamePolicy());
		Enumeration files = multi.getFileNames();
		int result = 0;
		
		while (files.hasMoreElements()) {
			String formName = (String) files.nextElement();
			String fileName = multi.getFilesystemName(formName);
			String originalFileName = multi.getOriginalFileName(formName);
			
			String title = multi.getParameter("title");
			String writer = multi.getParameter("writer");
			String content = multi.getParameter("content");
			content = content.replaceAll("\r\n", "<br />");

			
			// 노티스 정보 입력 후 다오로 삽입
			Notice notice = new Notice();
			notice.setTitle(title);
			notice.setWriter(writer);
			notice.setContent(content);
			notice.setFilesrc(originalFileName);
			notice.setPath(fileName);
			
			Connection con = getConnection();
			NoticeDao dao = new NoticeDao(con);
			result = dao.insert(notice);
			close(con);
		}


		if (result == 0) {
			return "error.jsp";
		}

		return "redirect:notice.do?p=2";
	}
}
